#!/bin/bash

INTERVAL=5
E_BADARGS=65

function startSar {
	TESTID=$1
	mkdir -p ${OUTPUT_DIR}${TESTID}
	sar -o ${OUTPUT_DIR}${TESTID}/binary_results $INTERVAL > /dev/null 2>&1 &
	disown
	sleep 1
	PID=`pgrep "\bsar\b"`
	echo "sar was started with PID: $PID" 
}

function stopSar {
	pgrep "\bsar\b" > /dev/null
	if [ $? -eq 0 ]; then
		PID=`pgrep "\bsar\b"`
		kill -9 $PID > /dev/null 2>&1
		echo "sar with PID: $PID was killed"
	fi
}

function runAppToBeTested {
	TESTID=$1

	# .. do specific processing here to start the app
	APPPID=`echo "hello world!" > ${OUTPUT_DIR}${TESTID}/app.log 2>&1`

	echo "Application finished: $?"
}

function runPerfResults {
	TESTID=$1

	# execute the performance analysis tool
	java -jar ../target/performance-report-1.0.jar ${OUTPUT_DIR}${TESTID} ${OUTPUT_DIR}${TESTID}/binary_results $INTERVAL "Test: $TESTID" > ${OUTPUT_DIR}${TESTID}/perftool.log 2>&1

	echo "Performance analysis tool finished: $?"
}

function runTest {
	TESTID=$1

	echo "starting sar"
	startSar $TESTID
	
	echo "waiting 15 seconds for samples to accumulate to indicate normal situation"
	sleep 15

	echo "now starting application"
	runAppToBeTested $TESTID

	echo "stopping sar"
	stopSar

	echo "creating performance results"
	runPerfResults $TESTID	
}

if [ ! -n "$1" ] || [ ! -n "$2" ]
then
  echo "Usage: `basename $0` 'output-dir' [ ALL | TESTID ]"
  echo "output-dir is the directory where results will be output"
  echo "ALL = Run all tests in this script"
  echo "TESTID = Run only one single test"
  exit $E_BADARGS
fi

# output dir is $1 plus a slash
OUTPUT_DIR=$1/

# This is the test or tests to be run. ALL means all tests
TEST_ID=$2

if [ "$TEST_ID" = "ALL" ]
then
	echo "Requested running all tests"
	runTest ID-1
	runTest ID-2
	runTest ID-3
	runTest ID-4
	runTest ID-5
	runTest ID-6
	runTest ID-7
	runTest ID-8
	runTest ID-9
	runTest ID-10
	runTest ID-11
else
	echo "Requested to run test $TEST_ID"
	runTest $TEST_ID
fi

